package com.egao.common.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.system.constants.YearConstants;
import com.egao.common.module.system.entity.Year;
import com.egao.common.module.system.mapper.YearMapper;
import com.egao.common.module.system.service.YearService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 毕业年份服务实现类
 * @author lym
 */
@Service
public class YearServiceImpl extends ServiceImpl<YearMapper, Year> implements YearService {

    @Override
    public JsonResult listAll() {
        List<Year> yearList = baseMapper.selectList(new QueryWrapper<Year>().orderByDesc("id"));
        return JsonResult.ok().setData(yearList);
    }

    @Override
    public Year getYear() {
        return baseMapper.selectOne(new QueryWrapper<Year>()
                .eq("state", YearConstants.STATE_TRUE)
                .orderByDesc("id")
                .last("limit 1")
        );
    }

    @Override
    public JsonResult insertYear(Year year) {
        if (year == null) {
            throw new ParameterException("参数异常");
        }

        Year oldYear = baseMapper.selectById(year.getId());
        if (oldYear != null) {
            throw new BusinessException("毕业年份已存在，请勿重复添加");
        }

        year.setState(YearConstants.STATE_FALSE);
        baseMapper.insert(year);

        return JsonResult.ok();
    }

    @Override
    public JsonResult setGraduationYear(Year year) {
        if (year == null) {
            throw new ParameterException("参数异常：未接收到毕业年份");
        }

        year = baseMapper.selectById(year.getId());
        if (year == null) {
            throw new BusinessException("参数异常：未找到毕业年份");
        }

        Year falseYear = new Year();
        falseYear.setState(YearConstants.STATE_FALSE);
        baseMapper.update(falseYear, new UpdateWrapper<>());

        year.setState(YearConstants.STATE_TRUE);
        baseMapper.update(year, new UpdateWrapper<Year>().eq("id", year.getId()));

        return JsonResult.ok();
    }

    @Override
    public List<Integer> yearAndLastYear() {
        List<Year> yearList = baseMapper.selectList(new QueryWrapper<Year>().orderByDesc("id"));
        List<Integer> years = new ArrayList<>();
        boolean last = false;
        for (Year item : yearList) {
            if (last) {
                years.add(item.getId());
                break;
            }
            if (YearConstants.STATE_TRUE.equals(item.getState())) {
                years.add(item.getId());
                last = true;
            }
        }
        return years;
    }
}
